import { reactive, ref } from 'vue'
import { getIconList } from '@/assets/icons/iconsData'

export function useForm() {
  const initialValues = {
    code: null as string | null,
    name: '',
    description: '',
    status: 1,
    menuCodes: [] as any[],
    dataPermissionDataList: [] as any[]
  }

  const state = reactive({
    detailFormRef: ref(),
    detailForm: { ...initialValues }
  })

  const meta = {
    model: state.detailForm,
    menuIconList: reactive<any[]>([]),
    rules: {
      name: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
      inputNum: [
        { required: true, message: '内容不能为空', trigger: 'blur' },
        { type: 'number', message: '内容必须为数字值', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '内容不能为空', trigger: 'blur' },
        { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: ['blur', 'change'] },
        { pattern: /^[a-zA-Z0-9_-]{6,16}$/, message: '密码只支持字母、数字和下划线', trigger: ['blur', 'change'] }
      ]
    }
  }

  const initForm = () => {
    state.detailForm = { ...initialValues }
    const menuIconListData = getIconList()
    menuIconListData.forEach(icon => {
      meta.menuIconList.push({
        label: icon,
        value: icon
      })
    })
  }

  const resetForm = () => {
    state.detailForm = { ...initialValues }
  }

  const getFormValues = () => state.detailForm

  const setDetail = (record: any) => {
    state.detailForm = { ...record }
  }

  return {
    meta,
    state,
    setDetail,
    initForm,
    resetForm,
    getFormValues
  }
}
